#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""最简单的代码审查测试文件"""

import os
from pathlib import Path
from typing import Optional

from code_review import (
    CodeReviewAssistant,
    ImprovementSuggestion,
)
from simple_pipe import ClaudeError, ClaudeProcessError


def build_demo_diff() -> str:
    """构造一个简单的统一 diff，用于演示和测试。"""
    diff_lines = [
        "diff --git a/sample.py b/sample.py",
        "index 1111111..2222222 100644",
        "--- a/sample.py",
        "+++ b/sample.py",
        "@@ -1,7 +1,11 @@",
        "-def add(a, b):",
        "+def add_numbers(a, b):",
        "+    if a is None or b is None:",
        "+        return 0",
        "     return a +++ b",
        " ",
        " ",
        " def calculate(value, other):",
        "-    result = add(value, other)",
        "+    result = add_numbers(value, other)",
        "+    debug = eval(\"value + other\")",
        "+    print(\"debug\", debug)",
        "     return result",
    ]
    return "\n".join(diff_lines) + "\n"


def discover_repo_root(start: Path) -> Optional[Path]:
    """向上查找 Git 仓库根目录，找不到则返回 None。"""
    for candidate in (start,) + tuple(start.parents):
        if (candidate / ".git").exists():
            return candidate
    return None
    """以友好的格式输出模拟评审结果。"""
    print("✅ 模拟代码审查完成！\n")
    print(f"📊 摘要: {result.summary}")
    print(
        f"📈 统计: 修改文件 {result.diff_stats.get('files_changed', 0)} 个，"
        f"新增 {result.diff_stats.get('lines_added', 0)} 行，"
        f"删除 {result.diff_stats.get('lines_removed', 0)} 行"
    )

    if not result.suggestions:
        print("ℹ️ 未发现需要改进的内容。")
        return

    print("\n🛠️ 改进建议：")
    for idx, suggestion in enumerate(result.suggestions, 1):
        _print_suggestion(idx, suggestion)


def _print_suggestion(index: int, suggestion: ImprovementSuggestion) -> None:
    """打印单条模拟建议的详细信息。"""
    print("-" * 60)
    print(
        f"{index}. [{suggestion.severity.upper()}] {suggestion.summary}"
        f" (文件: {suggestion.file_path}"
        f" 行: {suggestion.line_number or '未知'})"
    )
    print(f"原因: {suggestion.rationale}")
    print("\n原始代码:")
    print("```python")
    print(suggestion.original_code or "<空>")
    print("```")
    print("\n修改后代码:")
    print("```python")
    print(suggestion.modified_code or "<空>")
    print("```")


def main() -> None:
    """运行简单的代码审查测试。"""
    assistant = CodeReviewAssistant()
    repo_default = Path(__file__).resolve().parent
    repo_path = discover_repo_root(repo_default) or repo_default
    diff_content = build_demo_diff()

    # 降低真实 CLI 失败时的冗余重试噪音
    assistant.claude_cli.config.retry_attempts = 1

    print("🚀 开始代码审查测试")
    print("=" * 40)

    if (repo_path / ".git").exists():
        print(f"📂 使用 Git 仓库路径: {repo_path}")
    else:
        print(f"⚠️ 未找到 .git 目录，将使用: {repo_path}")

    try:
        result = assistant.review_diff(diff_content, str(repo_path))
        print("✅ 真实 Claude CLI 审查完成！\n")
        print(assistant.format_review_result(result, "detailed"))
        return

    except ClaudeProcessError as exc:
        print(f"❌ 真实 Claude CLI 执行失败，返回码 {exc.returncode}")
        if exc.stderr:
            print("🧾 CLI stderr 输出:")
            print(exc.stderr.strip())
        else:
            print("🧾 CLI 未返回 stderr 输出，请检查 Claude CLI 日志或配置。")

    except (ClaudeError, ValueError, FileNotFoundError) as exc:
        print(f"❌ 真实 Claude CLI 未完成: {exc}")


if __name__ == "__main__":
    main()
